import os
from flask import Flask, request, redirect, render_template, url_for, flash
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = {'html'}
CLASS_SECRET_CODE = "szpt2025cloud" # 可自定义班级口令

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 # 限制上传大小为2MB
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = 'a_strong_secret_key0'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/wall')
def resume_wall():
    try:
        all_files = os.listdir(app.config['UPLOAD_FOLDER'])
        html_files = sorted([f for f in all_files if f.endswith('.html')])
        return render_template('wall.html', resumes=html_files)
    except FileNotFoundError:
        return render_template('wall.html', resumes=[])

@app.route('/upload', methods=['POST'])
def upload_file():
    if request.form.get('secret_code') != CLASS_SECRET_CODE:
        flash('班级口令错误！')
        return redirect(url_for('upload_form'))
    
    if 'file' not in request.files or not request.form.get('student_name'):
        flash('姓名和文件不能为空')
        return redirect(request.url)
    
    file = request.files['file']
    student_name = request.form.get('student_name')

    if file and allowed_file(file.filename):
        final_filename = f"{secure_filename(student_name)}.html"
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], final_filename)
        
        if os.path.exists(file_path):
            flash(f"错误：文件 '{final_filename}' 已存在！")
            return redirect(url_for('upload_form'))

        file.save(file_path)
        
        return f"上传成功！<a href='/wall' target='_blank'>点击查看简历墙</a>。<br><a href='/'>返回上传</a>"

    flash('文件类型不允许')
    return redirect(request.url)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)